package com.jdy.haoduoaiteacher.util;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.os.Build;
import android.os.Environment;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.StatFs;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.jdy.haoduoaiteacher.MyTeacherApp;
import com.jdy.haoduoaiteacher.model.LeMachine;
import com.jdy.haoduoaiteacher.model.LeUser;
import com.jdy.haoduoaiteacher.util.animation.Rotate3dAnimation;
import com.ycsj.goldmedalnewconcept.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * @author hufei
 * 
 */
@SuppressLint("SimpleDateFormat")
public class Tools {
  public final static String TAG = Tools.class.getName();

  public static final String MTK_PLATFORM_KEY = "ro.mediatek.platform";

  public static final int NETWORK_TYPE_WIFI = 0;
  public static final int NETWORK_TYPE_MOBILE = 1;

  private static long lastClickTime;

  public static Date getDateAfter(Date d,int day){
    Calendar now =Calendar.getInstance();
    now.setTime(d);
    now.set(Calendar.DATE,now.get(Calendar.DATE)+day);
    return now.getTime();
  }


  //  String pTime = "2012-03-12";
  public static String getWeek(String pTime){

    String Week = "";
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Calendar cal = Calendar.getInstance();
    try {
      cal.setTime(format.parse(pTime));
    } catch (ParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

 //   Calendar cal = Calendar.getInstance();
    int i = cal.get(Calendar.DAY_OF_WEEK);
    switch (i) {
      case 1:
        return "周日";
      case 2:
        return "周一";
      case 3:
        return "周二";
      case 4:
        return "周三";
      case 5:
        return "周四";
      case 6:
        return "周五";
      case 7:
        return "周六";
      default:
        return "";
    }
  }

  public static boolean isFastDoubleClick() {
    long time = System.currentTimeMillis();
    long timeD = time - lastClickTime;
    if (0 < timeD && timeD < 1000) {

      return true;
    }
    lastClickTime = time;
    return false;

  }

  public static String ascii2native(String asciicode) {
    String[] asciis = asciicode.split("\\\\u");
    String nativeValue = asciis[0];
    try {
      for (int i = 1; i < asciis.length; i++) {
        String code = asciis[i];
        nativeValue += (char) Integer.parseInt(code.substring(0, 4), 16);
        if (code.length() > 4) {
          nativeValue += code.substring(4, code.length());
        }
      }
    } catch (NumberFormatException e) {
      return asciicode;
    }
    return nativeValue;
  }

  public static String toHexString(byte[] bytes) {
    StringBuilder hexString = new StringBuilder();
    for (byte b : bytes) {
      String str = Integer.toHexString(0xFF & b);
      while (str.length() < 2) {
        str = "0" + str;
      }
      hexString.append(str);
    }
    return hexString.toString();
  }

  public static String getCurrentTime(String format) {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
    String currentTime = sdf.format(date);
    return currentTime;
  }

  public static String getCurrentTime() {
    return getCurrentTime("yyyy-MM-dd  HH:mm:ss");
  }

  /**
   * convert dip to pixels
   * 
   */
  public static int getPixelByDip(Context context, int dip) {
    return (int) (context.getResources().getDisplayMetrics().density * dip + 0.5f);
  }

  public static int getPixBySp(Context ctx, int sp) {
    float v = ctx.getResources().getDisplayMetrics().scaledDensity;
    return (int) (v * sp + 0.5f);
  }

  public static int getScreenWidth(Context ctx) {
    return ctx.getResources().getDisplayMetrics().widthPixels;
  }

  public static int getScreenHeight(Context ctx) {
    return ctx.getResources().getDisplayMetrics().heightPixels;
  }

  /**
   * convert dip to pixels
   * 
   */
  public static int getPixelFByDip(Context context, float dip) {
    return (int) (context.getResources().getDisplayMetrics().density * dip);
  }

  public static boolean isEmpty(Object string) {
    if (string == null || "".equals(string) || "null".equals(string)) {
      return true;
    }
    return false;
  }

  public static boolean isNullStr(Object string) {
    if (string == null || "".equals(string) || "null".equals(string)) {
      return true;
    }
    return false;
  }

  public static boolean isNotNullStr(Object string) {
    return !isNullStr(string);
  }

  public static boolean isNotEmpty(Object string) {
    return !isEmpty(string);
  }

  public static String getNotEmptyString(String str) {
    if (str == null) {
      return "";
    } else {
      return str;
    }
  }

  public static int measureTextHeight(Paint paint) {
    FontMetrics fm = paint.getFontMetrics();
    return (int) (Math.ceil(fm.descent - fm.ascent) + 2);
  }

  public static int getPackageVersionCode(Context context)
      throws NameNotFoundException {
    String name = context.getPackageName();
    PackageInfo pinfo = context.getPackageManager().getPackageInfo(name,
        PackageManager.GET_CONFIGURATIONS);
    return pinfo.versionCode;
  }

  public static boolean isMobileNO(String mobiles) {
    Pattern p = Pattern.compile("^\\d{11}$");
    Matcher m = p.matcher(mobiles);
    return m.matches();
  }

  public static boolean isEmailValid(String email) {

    // String
    // str="^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$";
    // Pattern p = Pattern.compile(str);
    // Matcher m = p.matcher(email);
    // return m.matches();
    boolean result = false;
    if (!Tools.isEmpty(email) && email.contains("@") && email.contains(".")) {
      int index = email.indexOf("@");
      if (index != -1 && index != 0 && index != email.length()) {
        index = email.indexOf(".");
        if (index != -1 && index != 0 && index != email.length()) {
          result = true;
        }
      }
    }
    return result;
  }

  public static float strToFloat(String value) {
    float result = 0.00f;
    try {
      result = Float.parseFloat(value);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }

  public static int strToInt(Object value) {
    int result = 0;
    try {
      result = Integer.parseInt(value + "");
    } catch (Exception e) {
      // e.printStackTrace();
    }
    return result;
  }

  public static boolean floatEquals(float a, float b) {
    if (a < b + 0.000001f && a > b - 0.000001f) {
      return true;
    }
    return false;
  }

  public static long strToLong(String value) {
    long result = 0L;
    try {
      result = Long.parseLong(value);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }

  public static int getStatusBarHeight(Context ctx) {
    Class<?> c = null;
    Object obj = null;
    Field field = null;
    int x = 0;
    int statusBarHeight = 0;
    try {
      c = Class.forName("com.android.internal.R$dimen");
      obj = c.newInstance();
      field = c.getField("status_bar_height");
      x = Tools.strToInt(field.get(obj).toString());
      statusBarHeight = ctx.getResources().getDimensionPixelSize(x);
      return statusBarHeight;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return statusBarHeight;
  }

  public static boolean isAppOnForeground(Context context) {
    String packageName = context.getPackageName();
    ActivityManager manager = (ActivityManager) context
        .getSystemService(Context.ACTIVITY_SERVICE);
    // Returns a list of application processes that are running on the device
    List<RunningAppProcessInfo> appProcesses = manager.getRunningAppProcesses();
    if (appProcesses == null) {
      return false;
    }
    for (RunningAppProcessInfo appProcess : appProcesses) {
      if (appProcess.processName.equals(packageName)
          && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
        return true;
      }
    }
    return false;
  }

  public static boolean checkInstalledApp(Context context, String appName) {
    if (TextUtils.isEmpty(appName)) {
      return false;
    }
    PackageInfo packageInfo;

    try {
      packageInfo = context.getPackageManager().getPackageInfo(appName, 0);

    } catch (NameNotFoundException e) {
      packageInfo = null;
      e.printStackTrace();
    }
    if (packageInfo == null) {
      return false;
    } else {
      return true;
    }
  }

  public static boolean isEmulator(Context context) {
    String android_id = Settings.Secure.getString(context.getContentResolver(),
        Settings.Secure.ANDROID_ID);
    boolean emulator = TextUtils.isEmpty(android_id)
        || Build.PRODUCT.contains("sdk")
        || Build.FINGERPRINT.startsWith("generic");
    return emulator;
  }

  public static int getNavigationBarHeight(Context context) {
    int resourceId = context.getResources().getIdentifier(
        "navigation_bar_height", "dimen", "android");
    if (resourceId > 0) {
      return context.getResources().getDimensionPixelSize(resourceId);
    }
    return 0;
  }

  public static void writeLog(String fileName, String str) {
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
      File file = new File(Environment.getExternalStorageDirectory()
          + "/LeBaoApp/" + fileName);
      if (!file.getParentFile().exists()) {
        file.getParentFile().mkdirs();
      }
      BufferedReader reader = null;
      PrintWriter pw = null;
      try {
        reader = new BufferedReader(new StringReader(str + "\n"));
        pw = new PrintWriter(new BufferedOutputStream(new FileOutputStream(
            file, true)), true);
        char[] buf = new char[1024];
        int len = -1;
        if ((len = reader.read(buf)) != -1) {
          pw.write(buf, 0, len);
        }

      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        if (reader != null) {
          try {
            reader.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
        if (pw != null) {
          try {
            pw.close();
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
    }
  }

  public static String hashMapToJson(HashMap map) {
    String string = "{";
    for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
      Entry e = (Entry) it.next();
      string += "'" + e.getKey() + "':";
      string += "'" + e.getValue() + "',";
    }
    string = string.substring(0, string.lastIndexOf(","));
    string += "}";
    return string;
  }

  public static HashMap<String, Object> JsonObject2HashMap(JSONObject jsonObject)
      throws JSONException {
    HashMap<String, Object> result = new HashMap<String, Object>();
    Iterator<String> iterator = jsonObject.keys();
    String key = null;
    String value = null;
    while (iterator.hasNext()) {
      key = iterator.next();
      value = jsonObject.getString(key);
      result.put(key, value);
    }
    return result;
  }

  private void forceStopAPK(String pkgName) {
    Process sh = null;
    DataOutputStream os = null;
    try {
      sh = Runtime.getRuntime().exec("su");
      os = new DataOutputStream(sh.getOutputStream());
      final String Command = "am force-stop " + pkgName + "\n";
      os.writeBytes(Command);
      os.flush();

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    try {
      sh.waitFor();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  public String getTopActivityName(Context ctx) {
    String topActivityClassName = null;
    ActivityManager activityManager = (ActivityManager) ctx
        .getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> runningTaskInfos = activityManager.getRunningTasks(1);
    if (runningTaskInfos != null) {
      ComponentName f = runningTaskInfos.get(0).topActivity;
      topActivityClassName = f.getClassName();
    }
    return topActivityClassName;
  }

  public static boolean isNetworkAvailable(Context context) {
    State mobile = null;
    State wifi = null;
    try {
      ConnectivityManager manager = (ConnectivityManager) context
          .getSystemService(Context.CONNECTIVITY_SERVICE);
      // mobile 3G Data Network
      mobile = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
          .getState();
      // wifi
      wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
    } catch (Exception e) {
      // TODO: handle exception
    }

    // 如果3G网络和wifi网络都未连接，且不是处于正在连接状态 则进入Network Setting界面 由用户配置网络连接
    if (mobile == State.CONNECTED || mobile == State.CONNECTING)
      return true;
    if (wifi == State.CONNECTED || wifi == State.CONNECTING)
      return true;

    return false;
  }

  /**
   * In order to adapt different size of screen ,we should take considering the
   * device's dpi. Here,we set 480dpi(1080 * 1920) as the stone example.
   * 
   * @param context
   * @return
   */
  public static float getPixelRatio(Context context) {
    DisplayMetrics dm = context.getResources().getDisplayMetrics();
    int screenWidth = dm.widthPixels;
    int screenHeight = dm.heightPixels;
    float ratioWidth = (float) screenWidth / 1080;
    float ratioHeight = (float) screenHeight / 1920;
    float ratio = Math.min(ratioWidth, ratioHeight);
    return ratio;
  }

  /**
   * Check whether the device has camera hardware or not.
   * 
   * @param context
   * @return
   */
  public static boolean checkCameraHardware(Context context) {
    if (context.getPackageManager().hasSystemFeature(
        PackageManager.FEATURE_CAMERA)) {
      // this device has a camera
      return true;
    } else {
      // no camera on this device
      return false;
    }
  }

  /**
   * Check whether the permission to access has been granted.
   * 
   * @param context
   * @param permissionToBeChecked
   *          the permission to be checked.
   * @return
   */
  public static boolean checkPermission(Context context,
      String permissionToBeChecked) {
    PackageManager pm = context.getPackageManager();
    if (pm.checkPermission(permissionToBeChecked, context.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
      return true;
    } else {
      return false;
    }
  }

  public static String toHexString2(byte[] b) {
    /*
     * String str = new String(b); System.out.println(str); try { //b =
     * str.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { // TODO
     * Auto-generated catch block e.printStackTrace(); }
     */
    StringBuilder sb = new StringBuilder(b.length * 2);
    for (int i = 0; i < b.length; i++) {
      sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]);
      sb.append(HEX_DIGITS[b[i] & 0x0f]);
    }
    return sb.toString();
  }

  private static final char HEX_DIGITS[] = { '0', '1', '2', '3', '4', '5', '6',
      '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

  public static String getMD5(String message) {
    String digest = "";
    try {
      byte[] bytes = getMD5Bytes(message);
      digest = toHexString2(bytes);
      digest = digest.toLowerCase(Locale.CHINA);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return digest;
  }

  public static String getMd5Key(String str) {
    String keyStr;
    try {
      final MessageDigest mDigest = MessageDigest.getInstance("MD5");
      mDigest.update(str.getBytes());
      keyStr = bytesToHexString(mDigest.digest());
    } catch (NoSuchAlgorithmException e) {
      keyStr = String.valueOf(str.hashCode());
    }
    return keyStr;
  }

  public static String bytesToHexString(byte[] bytes) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < bytes.length; i++) {
      String hex = Integer.toHexString(0xFF & bytes[i]);
      if (hex.length() == 1) {
        sb.append('0');
      }
      sb.append(hex);
    }
    return sb.toString();
  }

  public static byte[] getMD5Bytes(String message) {
    byte[] digest = null;
    try {
      MessageDigest algorithm = MessageDigest.getInstance("MD5");
      algorithm.reset();
      algorithm.update(message.getBytes("UTF-8"));
      digest = algorithm.digest();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return digest;
  }

  public static boolean saveSetting(Context context, String key, String value,
      boolean secret) {
    try {
      if (secret && !TextUtils.isEmpty(value)) {
        value = Base64.encode(AES.encrypt(getMD5Bytes(key), value.getBytes()));
      }
      Settings.System.putString(context.getContentResolver(), key, value);
      return true;
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return false;
  }

  public static String loadSetting(Context context, String key, boolean secret) {
    String value0 = Settings.System
        .getString(context.getContentResolver(), key);
    if (!secret) {
      return value0;
    }
    if (!TextUtils.isEmpty(value0)) {

      try {
        byte[] v = AES.decrypt(getMD5Bytes(key), Base64.decode(value0));
        String value = new String(v);
        return value;
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    return null;
  }

  public static WakeLock getWakeLock(Context context, String lockName) {
    PowerManager powerManager = (PowerManager) context
        .getSystemService(Context.POWER_SERVICE);
    WakeLock wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK,
        lockName);
    return wakeLock;
  }

  public static Rotate3dAnimation get3DRotationAnim(int width, int height,
      float start, float end) {
    // Find the center of the container
    final float centerX = width / 2.0f;
    final float centerY = height / 2.0f;

    // Create a new 3D rotation with the supplied parameter
    // The animation listener is used to trigger the next animation
    final Rotate3dAnimation rotation = new Rotate3dAnimation(start, end,
        centerX, centerY, 310.0f, true, true);
    rotation.setDuration(500);
    rotation.setFillAfter(false);
    rotation.setInterpolator(new AccelerateInterpolator());
    return rotation;
  }

  /**
   * 默认绕Y轴
   * 
   * @param width
   * @param height
   * @param start
   * @param end
   * @return
   */
  public static Rotate3dAnimation get3DRotationAnim(int width, int height,
      float start, float end, boolean isRY) {
    // Find the center of the container
    final float centerX = width / 2.0f;
    final float centerY = height / 2.0f;

    // Create a new 3D rotation with the supplied parameter
    // The animation listener is used to trigger the next animation
    // final Rotate3dAnimation rotation = new Rotate3dAnimation(start, end,
    // centerX, centerY, 310.0f, true, isRY);
    final Rotate3dAnimation rotation = new Rotate3dAnimation(start, end,
        centerX, centerY, 0.0f, true, isRY);

    rotation.setDuration(400);
    rotation.setFillAfter(false);
    rotation.setInterpolator(new AccelerateInterpolator());
    return rotation;
  }

  public static String getDate(String value, SimpleDateFormat format) {
    long date = 0;
    try {
      date = Long.valueOf(value);
    } catch (Exception e) {
    }

    if (date != 0) {
      Calendar ca = Calendar.getInstance();
      ca.setTime(new Date(date));
      return format.format(ca.getTime());
    } else {
      return "";
    }
  }

  public static void setListViewHeightBasedOnChildren(ListView listView) {

    ListAdapter listAdapter = listView.getAdapter();
    if (listAdapter == null) {
      return;
    }

    int totalHeight = 0;
    for (int i = 0, len = listAdapter.getCount(); i < len; i++) {// listAdapter.getCount()返回数据项的数目
      View listItem = listAdapter.getView(i, null, listView);
      if (Tools.isNotEmpty(listItem)) {
        listItem.measure(0, 0);// 计算子项View 的宽高
        totalHeight += listItem.getMeasuredHeight();// 统计所有子项的总高度
      }

    }

    if (totalHeight > 0) {
      LayoutParams params = listView.getLayoutParams();
      params.height = totalHeight
          + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
      listView.setLayoutParams(params);
    }

  }

  public static void setGridViewHeightBasedOnChildren(GridView gridView) {
    // 获取GridView对应的Adapter
    ListAdapter listAdapter = gridView.getAdapter();
    if (listAdapter == null) {
      return;
    }
    int rows;
    int columns = 0;
    int horizontalBorderHeight = 0;
    Class<?> clazz = gridView.getClass();
    try {
      // 利用反射，取得每行显示的个数
      Field column = clazz.getDeclaredField("mRequestedNumColumns");
      column.setAccessible(true);
      columns = (Integer) column.get(gridView);
      // 利用反射，取得横向分割线高度
      Field horizontalSpacing = clazz
          .getDeclaredField("mRequestedHorizontalSpacing");
      horizontalSpacing.setAccessible(true);
      horizontalBorderHeight = (Integer) horizontalSpacing.get(gridView);
    } catch (Exception e) {
      // TODO: handle exception
      e.printStackTrace();
    }
    // 判断数据总数除以每行个数是否整除。不能整除代表有多余，需要加一行
    if (listAdapter.getCount() % columns > 0) {
      rows = listAdapter.getCount() / columns + 1;
    } else {
      rows = listAdapter.getCount() / columns;
    }
    int totalHeight = 0;
    for (int i = 0; i < rows; i++) { // 只计算每项高度*行数
      View listItem = listAdapter.getView(i, null, gridView);
      listItem.measure(0, 0); // 计算子项View 的宽高
      totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
    }
    LayoutParams params = gridView.getLayoutParams();
    params.height = totalHeight + horizontalBorderHeight * (rows - 1);// 最后加上分割线总高度
    gridView.setLayoutParams(params);
  }

  public static String FormatMiss(long miss) {
    long hour = miss / (60 * 60 * 1000);
    long minute = (miss - hour * 60 * 60 * 1000) / (60 * 1000);
    long second = (miss - hour * 60 * 60 * 1000 - minute * 60 * 1000) / 1000;
    if (second >= 60) {
      second = second % 60;
      minute += second / 60;
    }
    if (minute >= 60) {
      minute = minute % 60;
      hour += minute / 60;
    }
    String sh = " ";
    String sm = " ";
    String ss = " ";
    if (hour < 10) {
      sh = "0" + String.valueOf(hour);
    } else {
      sh = String.valueOf(hour);
    }
    if (minute < 10) {
      sm = "0" + String.valueOf(minute);
    } else {
      sm = String.valueOf(minute);
    }
    if (second < 10) {
      ss = "0" + String.valueOf(second);
    } else {
      ss = String.valueOf(second);
    }
    // System.out.println(sh + sm + ss);
    //
    return sh + ":" + sm + ":" + ss;

  }

  public static void saveLeBaby(LeMachine lm) {
    if (lm == null) {
      return;
    }

    LePreference.getInstance().saveLeBabyInfo(lm);
  }

  public static LeMachine restoreLeBaby() {
    LeMachine lm = LePreference.getInstance().getLeBaby();

    if (lm != null) {
      MyTeacherApp.getInstance().setBaby(lm);
    }

    return lm;
  }

  public static void saveLeUser(LeUser lu) {
    if (lu == null) {
      return;
    }

    LePreference.getInstance().saveLeUserInfo(lu);
  }

  public static LeUser restoreLeUser() {
    LeUser lu = LePreference.getInstance().getLeUser();
    if (lu != null) {
      MyTeacherApp.getInstance().setUser(lu);
      LeConfig.isLogin = true;
    }

    return lu;
  }

  public static String getTimeFromInt(int time) {
    if (time <= 0) {
      return "0:00";
    }
    int secondnd = time / 60;
    int million = time % 60;
    String f = String.valueOf(secondnd);
    String m = million >= 10 ? String.valueOf(million) : "0"
        + String.valueOf(million);
    return f + ":" + m;
  }

  /**
   * 获取今天还剩下多少秒
   * @return
   */
  public static int getMiao(){
    Calendar curDate = Calendar.getInstance();
    Calendar tommorowDate = new GregorianCalendar(curDate
            .get(Calendar.YEAR), curDate.get(Calendar.MONTH), curDate
            .get(Calendar.DATE) + 1, 0, 0, 0);
    return (int)(tommorowDate.getTimeInMillis() - curDate .getTimeInMillis()) / 1000;
  }

  /**
   * 是否在06:00 - 22:00之间
   */
  public static boolean isDayTime() {
    boolean valid = true;
    try {
      Date date = new Date();
      SimpleDateFormat formater = new SimpleDateFormat("HH:mm", Locale.ENGLISH);
      String nowTime = formater.format(date);
      if (nowTime.compareTo("06:00") < 0 || nowTime.compareTo("22:00") > 0) {
        valid = false;
      }
    } catch (Exception e) {
    }

    return valid;
  }

  public static Bitmap ConvertToBitmap(InputStream is) {
    return BitmapFactory.decodeStream(is);
  }

  /**
   * Before access to Internet,ensure network is available.
   * 
   * @param context
   * @return
   */
  public static boolean isNetworkAvailable2(Context context) {
    ConnectivityManager connMgr = (ConnectivityManager) context
        .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
      return true;
    } else {
      return false;
    }
  }

  public static boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
      return true;
    }
    return false;
  }

  public static boolean isServiceRunning(Context mContext, String serviceName) {
    boolean isWork = false;
    ActivityManager myAM = (ActivityManager) mContext
        .getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningServiceInfo> myList = myAM.getRunningServices(40);
    if (myList.size() <= 0) {
      return false;
    }
    for (int i = 0; i < myList.size(); i++) {
      String mName = myList.get(i).service.getClassName().toString();
      if (mName.equals(serviceName)) {
        isWork = true;
        break;
      }
    }
    return isWork;
  }

  public static boolean isMediatekPlatform() {
    Class<?> classType = null;
    Method getMethod = null;
    String platform = null;
    try {
      if (classType == null) {
        classType = Class.forName("android.os.SystemProperties");
        getMethod = classType.getDeclaredMethod("get", String.class);
        try {
          platform = (String) getMethod.invoke(classType, MTK_PLATFORM_KEY);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return Tools.isNotEmpty(platform)
        && (platform.startsWith("MT") || platform.startsWith("mt"));
  }

  @SuppressWarnings("deprecation")
  public static void adjustDialogSize(Dialog dialog) {
    WindowManager m = (WindowManager) MyTeacherApp.getAppContext()
        .getSystemService("window");
    Display d = m.getDefaultDisplay();
    LayoutParams p = dialog.getWindow().getAttributes();
    p.width = (int) (d.getWidth() * 0.8);
    dialog.getWindow().setAttributes(
        (WindowManager.LayoutParams) p);
  }

  public static boolean isUsingGPRSConnection(Context ctx) {
    boolean haveConnectedMobile = false;

    ConnectivityManager cm = (ConnectivityManager) ctx
        .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
    for (NetworkInfo ni : netInfo) {
      if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
        if (ni.isConnected())
          haveConnectedMobile = true;
    }
    return haveConnectedMobile;
  }

  /**
   * change yyyy-MM-dd HH:mm:ss to yyyy-MM-dd
   */
  public static String changeTime(String time) {
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    Date date = null;
    try {
      date = format.parse(time);
    } catch (ParseException e) {
      e.printStackTrace();
    }
    return formatter.format(date);
  }

  public static boolean isAppOnForeground() {
    Context ctx = MyTeacherApp.getInstance().getApplicationContext();
    ActivityManager activityManager = (ActivityManager) ctx
        .getSystemService(Context.ACTIVITY_SERVICE);
    String packageName = ctx.getPackageName();

    List<RunningAppProcessInfo> appProcesses = activityManager
        .getRunningAppProcesses();
    if (appProcesses == null)
      return false;

    for (RunningAppProcessInfo appProcess : appProcesses) {
      if (appProcess.processName.equals(packageName)
          && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
        return true;
      }
    }

    return false;
  }

  // a integer to xx:xx:xx
  public static String secToTime(int time) {
    String timeStr = null;
    int hour = 0;
    int minute = 0;
    int second = 0;
    if (time <= 0)
      return "00:00";
    else {
      minute = time / 60;
      if (minute < 60) {
        second = time % 60;
        timeStr = unitFormat(minute) + ":" + unitFormat(second);
      } else {
        hour = minute / 60;
        if (hour > 99)
          return "99:59:59";
        minute = minute % 60;
        second = time - hour * 3600 - minute * 60;
        timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":"
            + unitFormat(second);
      }
    }
    return timeStr;
  }

  public static String unitFormat(int i) {
    String retStr = null;
    if (i >= 0 && i < 10)
      retStr = "0" + Integer.toString(i);
    else
      retStr = "" + i;
    return retStr;
  }

  public static Bitmap drawableToBitamp(Drawable drawable) {
    if (drawable instanceof BitmapDrawable) {
      BitmapDrawable bd = (BitmapDrawable) drawable;
      return bd.getBitmap();
    }
    int w = drawable.getIntrinsicWidth();
    int h = drawable.getIntrinsicHeight();
    Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, w, h);
    drawable.draw(canvas);
    return bitmap;
  }

  public static boolean isWifiConnected(Context context) {
    int networkState = 0;
    if (context != null) {
      ConnectivityManager conManager = (ConnectivityManager) context
          .getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo wifiInfo = conManager
          .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
      if (wifiInfo != null
          && (wifiInfo.getState() == State.CONNECTED || wifiInfo
              .getState() == State.CONNECTING)) {
        networkState = NETWORK_TYPE_WIFI;
      } else {
        networkState = NETWORK_TYPE_MOBILE;
      }
    }
    return networkState == NETWORK_TYPE_WIFI;
  }

  public static boolean isNetworkAvaible(Context context) {
    State mobile = null;
    State wifi = null;
    try {
      ConnectivityManager manager = (ConnectivityManager) context
          .getSystemService(Context.CONNECTIVITY_SERVICE);
      // mobile 3G Data Network
      mobile = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
          .getState();
      // wifi
      wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
    } catch (Exception e) {
      // TODO: handle exception
    }

    // 如果3G网络和wifi网络都未连接，且不是处于正在连接状态 则进入Network Setting界面 由用户配置网络连接
    if (mobile == State.CONNECTED || mobile == State.CONNECTING)
      return true;
    if (wifi == State.CONNECTED || wifi == State.CONNECTING)
      return true;

    return false;
  }

  public static boolean isNetworkAvaible2(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context
        .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
  }

  /**
   * 价格清零
   * 
   * @param str
   *          原始字符串
   * @return
   */
  public static String shortenRMB(float price) {
    try {
      if (price == (long) price) {
        return String.format(Locale.CHINA, "%d", (long) price);
      } else {
        return String.format(Locale.CHINA, "%.1f", price);
      }
    } catch (Exception e) {
      // TODO: handle exception
    }
    return "";
  }

  public static String shortenRMB(double price) {
    try {
      if (price == (long) price) {
        return String.format(Locale.CHINA, "%d", (long) price);
      } else {
        return String.format(Locale.CHINA, "%.1f", price);
      }
    } catch (Exception e) {
      // TODO: handle exception
    }
    return "";
  }

  public static boolean isEqual(Context context, Bitmap expectedBitmap,
      Bitmap actualBitmap) {
    int nonMatchingPixels = 0;
    int allowedMaxNonMatchPixels = 10;
    if (expectedBitmap == null || actualBitmap == null || context == null) {
      return false;
    }
    int[] expectedBmpPixels = new int[expectedBitmap.getWidth()
        * expectedBitmap.getHeight()];
    expectedBitmap.getPixels(expectedBmpPixels, 0, expectedBitmap.getWidth(),
        0, 0, expectedBitmap.getWidth(), expectedBitmap.getHeight());
    int[] actualBmpPixels = new int[actualBitmap.getWidth()
        * actualBitmap.getHeight()];
    actualBitmap.getPixels(actualBmpPixels, 0, actualBitmap.getWidth(), 0, 0,
        actualBitmap.getWidth(), actualBitmap.getHeight());
    if (expectedBmpPixels.length != actualBmpPixels.length) {
      return false;
    }
    for (int i = 0; i < expectedBmpPixels.length; i++) {
      if (expectedBmpPixels[i] != actualBmpPixels[i]) {
        nonMatchingPixels++;
      }
    }
    if (nonMatchingPixels > allowedMaxNonMatchPixels) {
      return false;
    }
    return true;
  }

  public static Bitmap readBitMap(Context context, int resId) {
    BitmapFactory.Options opt = new BitmapFactory.Options();
    opt.inPreferredConfig = Bitmap.Config.RGB_565;
    opt.inPurgeable = true;
    opt.inInputShareable = true;
    InputStream is = context.getResources().openRawResource(resId);
    return BitmapFactory.decodeStream(is, null, opt);
  }

  public static int compare_date(String DATE1, String DATE2) {

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    try {
      Date dt1 = df.parse(DATE1);
      Date dt2 = df.parse(DATE2);
      if (dt1.getTime() > dt2.getTime()) {
        System.out.println("dt1 在dt2前");
        return 1;
      } else if (dt1.getTime() < dt2.getTime()) {
        System.out.println("dt1在dt2后");
        return -1;
      } else {
        return 0;
      }
    } catch (Exception exception) {
      exception.printStackTrace();
    }
    return 0;
  }

  public static int getResourceId(String name) {
    try {
      Field field = R.drawable.class.getField(name);
      return Integer.parseInt(field.get(null).toString());

    } catch (Exception e) {
      e.printStackTrace();
    }
    return 0;
  }

  public static final String newString(int codePoint) {
    return new String(Character.toChars(codePoint));
  }

  public static String getSNO(Context context) {
    String sno = null;
    return sno;
  }

  public static boolean ExistSDCard() {
    if (Environment.getExternalStorageState().equals(
        Environment.MEDIA_MOUNTED)) {
      return true;
    } else
      return false;
  }

  @SuppressWarnings("deprecation")
  public static long getSDFreeSize() {
    // 取得SD卡文件路径
    File path = Environment.getExternalStorageDirectory();
    StatFs sf = new StatFs(path.getPath());
    // 获取单个数据块的大小(Byte)
    long blockSize = sf.getBlockSize();
    // 空闲的数据块的数量
    long freeBlocks = sf.getAvailableBlocks();
    // 返回SD卡空闲大小
    return (freeBlocks * blockSize) / 1024 / 1024; // 单位MB
  }

  public static String replaceBlank(String str) {
    String dest = "";
    if (str != null) {
      Pattern p = Pattern.compile("\\s*|\t|\r|\n");
      Matcher m = p.matcher(str);
      dest = m.replaceAll("");
    }
    return dest;
  }
}